

var SoDaoFriendOnline = {
    timer1: 0,
    timer2: 0,
    l_reftime: 60,          //长时间刷新间隔 单位(秒)
    s_reftime: 1,           //短时间刷新间隔 单位(秒)
    friendCount: 0,         //计数器
    newNoticeNum: 0,
    newMsgNum: 0,
    newSysNum: 0,
    myUserName: '',
    user: '',               //发送站内信时用,SoDaoMessage.sendMessage,无法剔除
    usermd: '',             //发送站内信时用,SoDaoMessage.sendMessage,无法剔除
    islogin: 1,             //是否登陆
    clickSysMsg: 0,         //是否点击过系统消息
    friendData: '',         //好友数据，点击在线好友才显示
    temp: 0,                //临时用
    closeUrl: "/Utility/CloseCrossSitePop",
    /*bottombar上所有控件id*/
    friend_btn_block: '#bot-click4',                //好友显示按键区域
    friend_list_block: '#my-apps-c',                //好友列表区域
    friend_list: '.bot-friend-list',                //好友列表ul上级
    friend_close: '#bot-close_4',                   //好友关闭
    friend_query_input: '#textfield',               //好友查询
    friend_count_span: '#span_friend',              //好友数
    bot_tip_num: '#informnum',                      //提示数提示
    bot_tip_btn_block: '#bot-click2',               //提示显示按键区域
    bot_tip_block: '#my-apps-a',                    //提示列表区域
    bot_tip_close: '#bot-close_2',                  //提示关闭
    system_btn_block: '#bot-click3',                //系统显示按键区域
    system_list_block: '#my-apps-b',                //系统列表区域
    system_close: '#bot-close_3',                   //系统显示按键区域
    system_num: '#sysmsgnum',                       //系统消息数            
    sns_btn_block: '#bot-click1',                   //sns应用显示按键区域
    sns_list_block: '#my-apps-s',                   //sns应用列表区域
    sns_close: '#bot-close_1',                      //sns应用显示按键区域
    bot_inform_list: '.bot-inform-list',            //提醒列表上级div

    /*bottombar上所有控件id*/

    /*功能*/
    /*初始化*/
    Init: function () {

        if (SoDaoFriendOnline.isMobile()) return;
        //暂停循环
        //if (SoDaoFriendOnline.timer1 != null) {
        //clearTimeout(SoDaoFriendOnline.timer1);
        //}
        //底部工具栏HTML生成
        SoDaoFriendOnline.BottomBar_Init();

        //ie6 定位
        SoDaoFriendOnline.iePositionFixed();

    },
    /*获取在线好友数据*/
    GetFriendOnlineData: function () {
        var ajax = {
            url: "/FriendOnline/GetFriendOnlineData", type: "get", dataType: "json", cache: false,
            success: function (data) {

                SoDaoFriendOnline.user = data.user;
                SoDaoFriendOnline.usermd = data.usermd;
                //获取在线好友数量
                SoDaoFriendOnline.friendCount = data.friendCount;

                //显示好友数
                SoDaoFriendOnline.SetFriendCount(SoDaoFriendOnline.friend_count_span);
                //刷新好友在线列表
                //SoDaoFriendOnline.RefFriendOnlineList(data.result);
                SoDaoFriendOnline.friendData = data.result;
                SoDaoFriendOnline.timer1 = window.setTimeout("SoDaoFriendOnline.GetFriendOnlineData()", SoDaoFriendOnline.l_reftime * 1000);
            },
            error: function (txt) {
                //clearTimeout(SoDaoFriendOnline.timer1);
                //alert(txt.responseText);
            }
        }
        $.ajax(ajax);
    },
    /*添加好友*/
    AddFriend: function (friendUserName) {
        var ajax = {
            url: "/FriendOnline/AddFriend", type: "POST", dataType: "json",
            data: { friendUserName: friendUserName },
            success: function (data) {
                return;
            },
            error: function (txt) {

                //alert(txt.responseText);
            }
        }
        $.ajax(ajax);
    },
    /*发送心跳包*/
    Online: function () {

        //以下必须控件加载完才执行
        if (SoDaoFriendOnline.islogin == 0) {
            return;
        }
        if (SoDaoFriendOnline.myUserName == '') {
            setTimeout(function () { SoDaoFriendOnline.Online(); }, 10 * 1000);
            return;
        }

        var ajax = {
            url: "/FriendOnline/Online?u=" + SoDaoFriendOnline.myUserName + "&init=true", type: "POST", dataType: "json", cache: false,
            success: function (data) {
                return;
            },
            error: function (txt) {
                //alert(txt.responseText);
            }
        }
        $.ajax(ajax);

        setTimeout(function () { SoDaoFriendOnline.Online_2(); }, 5 * 60 * 1000);
    },
    Online_2: function () {

        //以下必须控件加载完才执行
        if (SoDaoFriendOnline.islogin == 0) {
            return;
        }
        if (SoDaoFriendOnline.myUserName == '') {
            setTimeout(function () { SoDaoFriendOnline.Online(); }, 10 * 1000);
            return;
        }

        var ajax = {
            url: "/FriendOnline/Online?u=" + SoDaoFriendOnline.myUserName + "&init=false", type: "POST", dataType: "json", cache: false,
            success: function (data) {
                return;
            },
            error: function (txt) {
                //alert(txt.responseText);
            }
        }
        $.ajax(ajax);

        setTimeout(function () { SoDaoFriendOnline.Online_2(); }, 5 * 60 * 1000);
    },
    /*移除好友*/
    DelFriend: function (friendUserName) {
        var ajax = {
            url: "/FriendOnline/DelFriend", type: "POST", dataType: "json",
            data: { friendUserName: friendUserName },
            success: function (data) {
                return;
            },
            error: function (txt) {
                //alert(txt.responseText);
            }
        }
        $.ajax(ajax);
    },
    /*获取提醒通知列表*/
    NoticeListShow: function () {
        var ajax = {
            url: "/FriendOnline/GetNoticeList?ncount=" + SoDaoFriendOnline.newNoticeNum + "&mcount=" + SoDaoFriendOnline.newMsgNum, type: "get", dataType: "html", cache: false,
            success: function (data) {
                var html = data;
                var parent = $(SoDaoFriendOnline.bot_inform_list);
                parent.empty();
                $(parent).append($(html));

                SoDaoFriendOnline.GetMessageCount();
                //通知列表中a特殊处理,因为通知层retrun false;href属性无效;
                //通知层retrun false是因为document.click增加一个隐藏所有对象（包含通知层）事件，如果不加点击通知层就会隐藏当前通知层
                $(SoDaoFriendOnline.bot_inform_list + ' a').click(function () {
                    var _href = $(this).attr('href');
                    var _target = $(this).attr('_target');
                    if (_href.length > 2) {
                        if (_target == '_blank')
                            window.open(_href);
                        else
                            window.location.href = _href;
                    }
                })
            },
            error: function (txt) {
                //alert(txt.responseText);
            }
        };
        $.ajax(ajax);
    },
    /*刷新好友列表*/
    RefFriendOnlineList: function (e) {
        //好友列表
        var parent = $(SoDaoFriendOnline.friend_list_block + ' ul');
        $(parent).empty();
        var arr = eval(e);

        $(arr).each(function (index, val) {
            addDom(parent, val.friendUserNames, val.friendUserNicks, val.mdfriendUserNicks, val.friendImage, val.friendUserNamePY);
        });

        function addDom(parent, username, usernick, mdusername, friendImage, pinyin) {

            var imgSrc = '';
            //            if (friendImage.toLowerCase() == 'http://css.sodao.com/home/img/noface_middle.gif') {
            imgSrc = friendImage;
            //            } else {
            //                imgSrc = 'http://img.mysodao.com/header' + friendImage;
            //            }

            var html = '<li>';
            html += '<a href="#" onclick="javascript:SoDaoFriendOnline.WindowOpen(this)" url="http://i.sodao.com/' + username + '"; target="_blank" class="bot-home-page"><img src="http://css.sodao.com/home/img/space.png" class="homepage-ico" width="16" height="16" /></a>';
            html += '<a py="' + pinyin + '" a_user="' + username + '" a_usermd="' + mdusername + '" href="#" onclick="javascript:SoDaoFriendOnline.SendMessage(this);return false;" class="bot-avatar"><img src="' + imgSrc + '"  width="30" height="30" alt="" /></a>';
            html += '<a a_user="' + username + '" a_usermd="' + mdusername + '" title="' + usernick + '" href="#" onclick="javascript:SoDaoFriendOnline.SendMessage(this);return false;">' + (usernick.length > 6 ? usernick.substr(0, 6) + '...' : usernick) + '</a>';
            html += '</li>';
            var liNode = $(html);
            $(parent).append(liNode);
        }

        SoDaoFriendOnline.QueryFriendOnline();
    },
    WindowOpen: function (e, url) {
        if ($(e).attr('target') == '_blank') {

            window.open($(e).attr('url'));
        }
        else {
            window.location.href = $(e).attr('url');
        }
    },
    /*查询在线好友,并筛选*/
    QueryFriendOnline: function () {
        if ($(SoDaoFriendOnline.friend_query_input).length < 1) {
            return;
        }

        var key = $(SoDaoFriendOnline.friend_query_input).val().toUpperCase();
        $(SoDaoFriendOnline.friend_list + ' ul li ').each(function () {
            var py = $("a", $(this)).eq(1).attr("py").toUpperCase();
            var name = $("a", $(this)).eq(2).text().toUpperCase();
            //拼音
            if (py.indexOf(key) >= 0 || name.indexOf(key) >= 0) {
                $(this).show();
            }
            else {
                $(this).hide();
            }

        });
    },
    /*发站内信*/
    SendMessage: function (obj) {
        setTimeout(function () {
            SoDaoMessage.sendMessage(SoDaoFriendOnline.user, SoDaoFriendOnline.usermd, $(obj).attr("a_user"), $(obj).attr("a_usermd"), SoDaoFriendOnline.closeUrl);
        }, 10);
    },
    //获取通知和消息数
    GetMessageCount: function () {
        var ajax = {
            url: "/FriendOnline/GetUserMessageData", type: "get", dataType: "json", cache: false,
            success: function (data) {
                /* 取消消息提醒
                //SoDaoFriendOnline.newNoticeNum = data.newNoticeNum;
                //SoDaoFriendOnline.newMsgNum = data.newMsgNum; */
                SoDaoFriendOnline.newSysNum = data.newSysNum;
            }
        };
        $.ajax(ajax);
        setTimeout("SoDaoFriendOnline.GetMessageCount()", 30 * 60 * 1000);
    },
    /*设置显示好友数位置*/
    SetFriendCount: function (objname) {
        var _text = '在线好友(' + SoDaoFriendOnline.friendCount + ')';
        $(objname).text(_text);
    },
    /*获取底部工具条样式*/
    BottomBar_Init: function () {
        var ajax = {
            url: "/FriendOnline/GetBottomBarTemplate", type: "get", dataType: 'html', cache: false,
            success: function (req) {
                var bottombarHTML = req;
                var parentDiv = $(bottombarHTML);           //创建一个父DIV
                parentDiv.appendTo('body');                 //将父DIV添加到BODY中

                SoDaoFriendOnline.BindAllControlEvent();    //绑定所有控件事件

                // alert(SoDaoFriendOnline.islogin);
                //以下必须控件加载完才执行
                if (SoDaoFriendOnline.islogin == 0) {
                    return;
                }

                //获取在线好友数据
                SoDaoFriendOnline.GetFriendOnlineData();

                //获取站内信数量
                SoDaoFriendOnline.GetMessageCount();

            },
            error: function (req) {
                //alert(req.responseText);
            }
        }
        $.ajax(ajax);
    },
    SystemMessageShow: function () {
        //系统消息被加载过一次，等刷新页面后才能再次加载
        if (SoDaoFriendOnline.clickSysMsg == 1) {
            //alert('已被加载过');
            return;
        }

        $(SoDaoFriendOnline.system_list_block).empty();
        var ajax = {
            url: "/FriendOnline/GetSystemMessagePage", type: "get", dataType: 'html', cache: false,
            success: function (req) {
                var sysMsgHTML = req;
                var parentDiv = $(sysMsgHTML);                      //创建一个父DIV
                parentDiv.appendTo(SoDaoFriendOnline.system_list_block);                 //将父DIV添加到BODY中
                //加载过
                SoDaoFriendOnline.clickSysMsg = 1;
                //系统消息关闭事件，必须加载完成才能绑定
                $(SoDaoFriendOnline.system_close).click(function () {
                    SoDaoFriendOnline.AllHide();
                });
            },
            error: function (req) {

            }
        }
        $.ajax(ajax);

    },
    BindAllControlEvent: function () {
        //好友列表打开
        $(SoDaoFriendOnline.friend_btn_block).click(function () {
            if ($(SoDaoFriendOnline.friend_list_block).is(':hidden')) {
                SoDaoFriendOnline.AllHide();
                $(SoDaoFriendOnline.friend_list_block).fadeIn("fast"); //slideDown,fadeIn
                $(SoDaoFriendOnline.friend_btn_block).addClass("click-on").parent().css("z-index", "10002").siblings().css("z-index", "10001");

                $(SoDaoFriendOnline.friend_query_input).val('');
                SoDaoFriendOnline.RefFriendOnlineList(SoDaoFriendOnline.friendData);
            }
            else if ($(SoDaoFriendOnline.friend_list_block).is(':visible')) {
                SoDaoFriendOnline.AllHide();
            }
            this.blur();
        });

        //好友关闭
        $(SoDaoFriendOnline.friend_close).click(function () {
            SoDaoFriendOnline.AllHide();
        });

        //好友列表查询
        $(SoDaoFriendOnline.friend_query_input).keyup(function () {
            SoDaoFriendOnline.QueryFriendOnline();
        });

        //站内信列表打开
        $(SoDaoFriendOnline.bot_tip_btn_block).click(function () {
            if ($(SoDaoFriendOnline.bot_tip_block).is(':hidden')) {

                //显示通知信息
                SoDaoFriendOnline.NoticeListShow();
                SoDaoFriendOnline.AllHide();
                $(SoDaoFriendOnline.bot_tip_block).fadeIn("fast"); //slideDown,fadeIn
                $(SoDaoFriendOnline.bot_tip_btn_block).addClass("click-on").parent().css("z-index", "10002").siblings().css("z-index", "10001");
            }
            else if ($(SoDaoFriendOnline.bot_tip_block).is(':visible')) {
                SoDaoFriendOnline.AllHide();
                $(SoDaoFriendOnline.bot_tip_btn_block).removeClass("click-on");
            }
            this.blur();
        });

        //站内信列表关闭
        $(SoDaoFriendOnline.bot_tip_close).click(function () {
            SoDaoFriendOnline.AllHide();
        });

        //系统消息打开
        $(SoDaoFriendOnline.system_btn_block).click(function () {
            if ($(SoDaoFriendOnline.system_list_block).is(':hidden')) {
                //显示系统消息
                SoDaoFriendOnline.SystemMessageShow();
                SoDaoFriendOnline.AllHide();
                $(SoDaoFriendOnline.system_list_block).fadeIn("fast"); //slideDown,fadeIn
                $(SoDaoFriendOnline.system_btn_block).addClass("click-on").parent().css("z-index", "10002").siblings().css("z-index", "10001");
            }
            else if ($(SoDaoFriendOnline.system_list_block).is(':visible')) {
                SoDaoFriendOnline.AllHide();
            }
            this.blur();
        });

        //系统应用打开
        $(SoDaoFriendOnline.sns_btn_block).click(function () {
            if ($(SoDaoFriendOnline.sns_list_block).is(':hidden')) {
                SoDaoFriendOnline.AllHide();
                $(SoDaoFriendOnline.sns_list_block).fadeIn("fast"); //slideDown,fadeIn
                $(SoDaoFriendOnline.sns_btn_block).addClass("click-on").parent().css("z-index", "10002").siblings().css("z-index", "10001");
            }
            else if ($(SoDaoFriendOnline.sns_list_block).is(':visible')) {
                SoDaoFriendOnline.AllHide();
            }
            this.blur();
        });

        //系统应用关闭
        $(SoDaoFriendOnline.sns_close).click(function () {
            SoDaoFriendOnline.AllHide();
        });

        //点击其他区域关闭
        $(document).click(function () {
            SoDaoFriendOnline.AllHide();
        });

        //某些位置取消默认事件 如href='#'
        $("#bot-close_1,#bot-click1,#bot-close_3,.cut-pg-pev,.cut-pg-nex,#bot-click3,#bot-close_2,#bot-click2,#bot-close_4,#bot-click4,#my-apps-c,#my-apps-a,#my-apps-b,#my-apps-s").click(function (event) {
            //event.preventDefault();
            return false;
        });

        SoDaoFriendOnline.ShowMsgNum();

        //添加移动样式
        SoDaoFriendOnline.showHighlighting($("#bottom-bar .sns-app li,#bottom-bar .bot-friend-list li"));

    },
    //显示消息数
    ShowMsgNum: function () {
        var sumNum = parseInt(SoDaoFriendOnline.newMsgNum) + parseInt(SoDaoFriendOnline.newNoticeNum); //提醒中的条数


        if (sumNum > 0) {
            //            if (SoDaoFriendOnline.isIE6()) {
            //                $(SoDaoFriendOnline.bot_tip_num).show();
            //            }
            //            else
            $(SoDaoFriendOnline.bot_tip_num).fadeOut().fadeIn();

            $(SoDaoFriendOnline.bot_tip_num).html("<em>" + sumNum + "</em>");
        }
        else {
            $(SoDaoFriendOnline.bot_tip_num).stop(true);
            $(SoDaoFriendOnline.bot_tip_num).hide();
        }

        sumNum = parseInt(SoDaoFriendOnline.newSysNum);
        if (sumNum > 0) {
            //            if (SoDaoFriendOnline.isIE6()) {
            //                $(SoDaoFriendOnline.system_num).show();
            //            }
            //            else
            $(SoDaoFriendOnline.system_num).fadeOut().fadeIn();

            $(SoDaoFriendOnline.system_num).html("<em>" + sumNum + "</em>");
        }
        else {
            $(SoDaoFriendOnline.system_num).stop(true);
            $(SoDaoFriendOnline.system_num).hide();
        }

        //alert(sumNum);
        window.setTimeout("SoDaoFriendOnline.ShowMsgNum()", 1200);
    },
    //所有列表隐藏
    AllHide: function () {
        //slideUp,fadeOut
        $(SoDaoFriendOnline.bot_tip_block).hide(); //hide
        $(SoDaoFriendOnline.friend_list_block).hide(); //hide
        $(SoDaoFriendOnline.system_list_block).hide(); //hide
        $(SoDaoFriendOnline.sns_list_block).hide(); //hide

        $(SoDaoFriendOnline.sns_btn_block).removeClass("click-on");
        $(SoDaoFriendOnline.system_btn_block).removeClass("click-on");
        $(SoDaoFriendOnline.friend_btn_block).removeClass("click-on");
        $(SoDaoFriendOnline.bot_tip_btn_block).removeClass("click-on");
    },
    //IE6,BUG
    iePositionFixed: function () {
        $(window).scroll(function () {
            if (SoDaoFriendOnline.isIE6()) {
                //隐藏
                $('#bottom-bar').hide();
                clearTimeout(SoDaoFriendOnline.timer2);
                SoDaoFriendOnline.timer2 = setTimeout(function () {
                    $('#bottom-bar').show();
                }, 500);
            }
        });

        setInterval(function () {
            if (SoDaoFriendOnline.isIE6()) {
                $("#bottom-bar").css("position", "absolute").css("top", $(window).height() + $(document).scrollTop() - 26);

                //限制宽度不得低于900
                if ($(document.body)[0].clientWidth < 1000)
                    $('#bottom-bar').width(980);
                else
                    $('#bottom-bar').width('100%')
            }
        }, 50);

        if (SoDaoFriendOnline.isIE6()) {
            document.execCommand("BackgroundImageCache", false, true);
        }
    },
    showHighlighting: function (obj) {
        obj.live("mouseover", function () {
            $(this).addClass("hover");
        });
        obj.live("mouseout", function () {
            $(this).removeClass("hover");
        });
    },
    IsLogin: function () {
        var cookie_start = document.cookie.indexOf("sodao.userName");
        var cookie_end = document.cookie.indexOf(";", cookie_start);
        var username = cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
        //alert(document.cookie);
        //if (username == "") return false;
        return true;
    },
    isIE6: function () {
        if ($.browser.msie && ($.browser.version == "6.0") && !$.support.style) {
            return true;
        }
        return false;
    },
    isMobile: function () {

        var userAgent = navigator.userAgent.toString().toLowerCase();
        if (userAgent.indexOf('mobile') != -1) {
            return true;
        }
        return false;
    }

};

function substr(str, len) {
    if (!str || !len) { return ''; }
    //预期计数：中文2字节，英文1字节 
    var a = 0;
    //循环计数 
    var i = 0;
    //临时字串     
    var temp = '';
    for (i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 255) {
            //按照预期计数增加2 29.            
            a += 2;
        }
        else {
            a++;
        }
        //如果增加计数后长度大于限定长度，就直接返回临时字符串 
        if (a > len) { return temp; }
        //将当前内容加到临时字符串 
        temp += str.charAt(i);
    }
    //如果全部是单字节字符，就直接返回源字符串 
    return str;
}